import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/Conversation.dart';
import 'package:easy_chat_app/commons/model/GetContactsListItem.dart';
import 'package:easy_chat_app/commons/model/GetFriendRequestListResultData.dart';
import 'package:easy_chat_app/commons/model/Result.dart';
import 'package:easy_chat_app/commons/utils/ListUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/utils/StringUtils.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:easy_chat_app/mobile/page/MobileChatPage.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

import '../../commons/utils/HttpUtils.dart';

class MobileContactsPageDataChangeNotifier extends ChangeNotifier {
  Logger logger = Logger();

  List<GetContactsListItem> contactsList = [];

  List<ContactsView> contactsViewList = [];

  List<String> pyList = [];

  List<GetFriendRequestListResultDataFriendRequestView>? friendRequestViewList;

  int? currentUserId;

  int unreadFriendRequestViewCount = 0;

  Future<void> reload() async {
    var result = await HttpUtils.getContactsList();
    contactsList.clear();
    if (ListUtils.isNotEmpty(result.data)) {
      contactsList.addAll(result.data!);
    }
    logger.i("contactsList: $contactsList");
    convertGetContactsListItem2ContactsView();
    logger.i("contactsViewList: $contactsViewList");

    GetFriendRequestListResultData? resultData =
        (await HttpUtils.getFriendRequestList()).data;
    friendRequestViewList = resultData?.friendRequestViewList;
    currentUserId = resultData?.currentUserId;

    unreadFriendRequestViewCount = 0;
    friendRequestViewList?.forEach((item) {
      if (item.targetUserId == currentUserId && item.readStatus == 0) {
        unreadFriendRequestViewCount = unreadFriendRequestViewCount + 1;
      }
    });
    logger.i("friendRequestViewList:$friendRequestViewList");
    logger.i("unreadFriendRequestViewCount:$unreadFriendRequestViewCount");
    notifyListeners();
  }

  void convertGetContactsListItem2ContactsView() {
    Set<String> pySet = {};
    for (var value in contactsList) {
      if (value.nicknamePyPrefixLetter == null) {
        continue;
      }
      pySet.add(value.nicknamePyPrefixLetter!);
    }

    List<String> sortedPyList = pySet.toList();
    sortedPyList.sort((a, b) => a.compareTo(b));
    pyList.clear();
    pyList.addAll(sortedPyList);

    Map<String, List<GetContactsListItem>> groupedGetContactListItemMap = {};
    for (var value in contactsList) {
      var py = value.nicknamePyPrefixLetter;
      var getContactListItemList = groupedGetContactListItemMap[py];
      if (getContactListItemList == null) {
        groupedGetContactListItemMap[py!] = [];
      }
      getContactListItemList = groupedGetContactListItemMap[py];
      getContactListItemList!.add(value);
    }

    contactsViewList.clear();

    // 新的朋友选项
    ContactsView newFriend = ContactsView();
    newFriend.type = 2;
    newFriend.assetImg = "images/新的朋友.png";
    newFriend.typeCode = "newFriend";
    newFriend.typeName = "新的朋友";
    newFriend.showBorder = true;
    contactsViewList.add(newFriend);

    // 添加群聊选项
    ContactsView chatGroup = ContactsView();
    chatGroup.type = 2;
    chatGroup.assetImg = "images/群聊.png";
    chatGroup.typeCode = "chatGroup";
    chatGroup.typeName = "群聊";
    chatGroup.showBorder = false;
    contactsViewList.add(chatGroup);

    for (var py in sortedPyList) {
      var pyData = ContactsView();
      pyData.type = 0;
      pyData.py = py;
      contactsViewList.add(pyData);
      var getContactListItemList = groupedGetContactListItemMap[py];
      if (getContactListItemList != null) {
        for (int i = 0; i < getContactListItemList.length; i++) {
          var value = getContactListItemList[i];
          var contactsView = ContactsView();
          contactsView.type = 1;
          contactsView.contactId = value.id;
          contactsView.contactCode = value.code;
          contactsView.nickname = value.nickname;
          contactsView.headPortrait = value.headPortrait;
          contactsView.headPortraitStoreType = value.headPortraitStoreType;
          // logger.i("i: $i, length: ${getContactListItemList.length}");
          if (i + 1 == getContactListItemList.length) {
            contactsView.showBorder = false;
          }
          contactsViewList.add(contactsView);
        }
      }
    }
  }
}

class ContactsView {
  // 0 拼音 1 联系人 2 系统内置选项
  int? type;
  int? contactId;
  String? contactCode;
  String? typeCode;
  String? typeName;
  String? assetImg;
  String? py;
  String? nickname;
  String? headPortrait;
  String? headPortraitStoreType;
  bool showBorder = true;

  @override
  String toString() {
    return 'ContactsView{type: $type, contactId: $contactId, contactCode: $contactCode, typeCode: $typeCode, typeName: $typeName, assetImg: $assetImg, py: $py, nickname: $nickname, headPortrait: $headPortrait, headPortraitStoreType: $headPortraitStoreType, showBorder: $showBorder}';
  }
}

class MobileContactsPage extends StatelessWidget {
  final Logger logger = Logger();

  MobileContactsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) {
          var result = MobileContactsPageDataChangeNotifier();
          result.reload();
          return result;
        })
      ],
      builder: (context, child) {
        MobileContactsPageDataChangeNotifier contactsPageDataChangeNotifier =
            context.watch<MobileContactsPageDataChangeNotifier>();
        var appUserDetailChangeNotifier =
            context.watch<AppUserDetailChangeNotifier>();
        AppUserDetail appUserDetail =
            appUserDetailChangeNotifier.getAppUserDetail();
        List<ContactsView> contactsViewList =
            contactsPageDataChangeNotifier.contactsViewList;
        return ListView.builder(
            itemBuilder: (context, index) {
              ContactsView contactsView = contactsViewList[index];
              if (contactsView.type == 0) {
                return contentViewType0(contactsView);
              }
              if (contactsView.type == 1) {
                return contentViewType1(contactsView, appUserDetail);
              }
              if (contactsView.type == 2) {
                return contentViewType2(
                    contactsView, contactsPageDataChangeNotifier);
              }
              return Container();
            },
            itemCount: contactsViewList.length);
      },
    );
  }

  /// 拼音展示组件
  Widget contentViewType0(ContactsView contactsView) {
    return Container(
      padding: const EdgeInsets.only(left: 25, right: 25),
      color: const Color.fromRGBO(237, 237, 237, 1),
      alignment: Alignment.centerLeft,
      height: 30,
      child: Text(
        StringUtils.defaultIfEmpty(contactsView.py, "").toUpperCase(),
        style: const TextStyle(
            fontSize: 10, color: Color.fromRGBO(108, 108, 108, 1)),
      ),
    );
  }

  /// 通讯人展示
  Widget contentViewType1(
      ContactsView contactsView, AppUserDetail appUserDetail) {
    return GestureDetector(
      onTap: () async {
        logger.i("点击联系人: $contactsView");
        Result<Conversation?> conversationResult =
            await HttpUtils.getOrCreateConversation(
                LocalConversationTypeConstants.general,
                contactsView.contactId!,
                null);
        if (conversationResult.data == null) {
          logger.w("会话生成失败:$conversationResult");
          return;
        }
        Conversation conversation = conversationResult.data!;
        LocalConversation? localConversation =
            await LocalConversationService.getLocalConversationById(
                conversation.id!);
        if (localConversation == null) {
          localConversation = LocalConversation.create(
              id: conversation.id,
              uid1: conversation.uid1,
              uid2: conversation.uid2,
              type: LocalConversationTypeConstants.general,
              updateTime: DateTime.now().millisecondsSinceEpoch,
              unreadMsgCount: 0);
          await LocalConversationService.addLocalConversation(
              localConversation);
        }
        await RouteUtils.route2MobileChatPage(
          MobileChatPageParams(
              contactUserId: contactsView.contactId,
              contactUserCode: contactsView.contactCode,
              contactUserNickname: contactsView.nickname,
              contactUserHeadPortrait: contactsView.headPortrait,
              contactUserHeadPortraitStoreType:
                  contactsView.headPortraitStoreType,
              currentUserId: appUserDetail.id!,
              currentUserCode: appUserDetail.code,
              currentUserNickName: appUserDetail.nickname,
              currentUserHeadPortrait: appUserDetail.headPortrait,
              currentUserHeadPortraitStoreType:
                  appUserDetail.headPortraitStoreType,
              localConversation: localConversation),
        );
      },
      child: Container(
        padding: const EdgeInsets.only(left: 25),
        height: 50,
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.only(right: 15),
              alignment: Alignment.center,
              child: UserHeadPortrait.network(
                  size: 35,
                  userCode: contactsView.contactCode!,
                  userHeadPortrait: contactsView.headPortrait!,
                  userHeadPortraitStoreType:
                      contactsView.headPortraitStoreType!),
            ),
            Expanded(
                child: Container(
              decoration: contactsView.showBorder
                  ? const BoxDecoration(
                      border: Border(bottom: BorderSide(color: Colors.black12)))
                  : null,
              alignment: Alignment.centerLeft,
              child: Text(
                StringUtils.defaultIfEmpty(contactsView.nickname, ""),
                style: const TextStyle(fontSize: 16),
              ),
            ))
          ],
        ),
      ),
    );
  }

  /// 系统内置功能
  Widget contentViewType2(ContactsView contactsView,
      MobileContactsPageDataChangeNotifier contactsPageDataChangeNotifier) {
    String badgeLabelText = "";
    double badgeOpacity = 0;
    if (contactsView.typeCode == "newFriend" &&
        contactsPageDataChangeNotifier.unreadFriendRequestViewCount != 0) {
      badgeLabelText =
          "${contactsPageDataChangeNotifier.unreadFriendRequestViewCount}";
      badgeOpacity = 1;
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        logger.i("contactsView:$contactsView");
        if (contactsView.typeCode == "chatGroup") {
          await RouteUtils.route2MobileUserChatGroupListPage();
        }
        if (contactsView.typeCode == "newFriend") {
          await RouteUtils.route2MobileFriendRequestListPage(
              contactsPageDataChangeNotifier.friendRequestViewList);
          await contactsPageDataChangeNotifier.reload();
        }
      },
      child: Container(
        padding: const EdgeInsets.only(left: 25),
        height: 50,
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.only(right: 15),
              alignment: Alignment.center,
              child: Badge(
                label: Text(badgeLabelText),
                backgroundColor: Color.fromRGBO(247, 80, 80, badgeOpacity),
                child: SizedBox(
                  height: 35,
                  width: 35,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: Image.asset(contactsView.assetImg!),
                  ),
                ),
              ),
            ),
            Expanded(
                child: Container(
              decoration: contactsView.showBorder
                  ? const BoxDecoration(
                      border: Border(bottom: BorderSide(color: Colors.black12)))
                  : null,
              alignment: Alignment.centerLeft,
              child: Text(
                contactsView.typeName!,
                style: const TextStyle(fontSize: 16),
              ),
            ))
          ],
        ),
      ),
    );
  }
}
